//
//  ZSubmitMyOrderVC.m
//  DistributorAB
//
//  Created by LZY on 2019/10/11.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "ZSubmitMyOrderVC.h"

#import "ZOrderShipingAddressCell.h"//收货地址cell
#import "ZMyOrderShopInfoTopCell.h"//店铺名称cell
#import "ZMyOrderInfoCell.h"//预订产品信息cell

#import "ZMyOrderCarOrderModel.h"

#import "ZMyAddressVC.h"//收货地址列表
#import "ZMyOrderSubmitSuccessView.h"//提交预订成功提示
#import "ZMyAddressModel.h"

@interface ZSubmitMyOrderVC () <UITableViewDataSource,UITableViewDelegate,ZMyAddressVCDelegate,ZMyOrderSubmitSuccessViewDelegate>
{
    __block BOOL _isRequesting;//是否正在请求数据
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZMyAddressModel *addressModel;//选择的收获地址
@property (nonatomic, assign) BOOL haveSelectedAddress;
@property (nonatomic, assign) NSString *is_default;
@end

@implementation ZSubmitMyOrderVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (!self.addressModel) {
        [self checkUserAddressList];
    }
    
    
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    //置空
    self.haveSelectedAddress = NO;
    self.is_default = @"0";
    self.addressModel = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提交预订单";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    
    [self setupViewAction];
}
#pragma mark - 请求经销商地址列表
- (void)checkUserAddressList{

    [NetWorkTool POST:checkAddressList param:nil success:^(id dic) {
        
        NSArray *addressArray = [dic objectForKeyNotNil:@"data"];
        [addressArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           ZMyAddressModel *model = [ZMyAddressModel mj_objectWithKeyValues:obj];
            NSString *isDefault = [NSString stringWithFormat:@"%@", model.is_default];
            if (isDefault.length == 0 || [isDefault isEqualToString:@"0"])
            {
                
            }
            else if ([model.is_default isEqualToString:@"1"]) {

                    //存储默认收获地址
                    NSData *addressData = [NSKeyedArchiver archivedDataWithRootObject:model];
                    [USER_DEFAULT setObject:addressData forKey:DEFAULT_ADDRESS];
                    [USER_DEFAULT synchronize];
                    self.addressModel = model;
                     [self.tableView reloadData];
                    return ;
            }
            else
            {   //没有选择 并且 没有设置过默认
                if (self.haveSelectedAddress == NO && [self.is_default isEqualToString:@"0"])
                {
                    //请求接口 存在默认的 显示默认的
                    if (self.addressModel) {
                        self.addressModel = model;
                        [self.tableView reloadData];
                        return ;
                    } else  {
                        self.addressModel = nil;
                    }
                }
                //有选择 或者 设置过默认
                else {
                    if (self.addressModel.user_name.length>0||self.addressModel.phone.length>0||self.addressModel.address.length>0) {
                        
                        
                    }
                }
            }
        }];
        [self.tableView reloadData];
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        self.addressModel = nil;
        [self.tableView reloadData];
    } fail:^(NSError *error) {
        self.addressModel = nil;
        [self.tableView reloadData];
    } needUser:YES];
}
#pragma mark - 界面布局
- (void)setupViewAction{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, kScreen_Width, kScreen_Height - kNaviHeight - 44 - TabbarSafeBottomMargin) style:UITableViewStylePlain];
    _tableView.backgroundColor = kColorWithHex(0xf2f2f2);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[ZOrderShipingAddressCell class] forCellReuseIdentifier:NSStringFromClass([ZOrderShipingAddressCell class])];
    [_tableView registerClass:[ZMyOrderShopInfoTopCell class] forCellReuseIdentifier:NSStringFromClass([ZMyOrderShopInfoTopCell class])];
    [_tableView registerClass:[ZMyOrderInfoCell class] forCellReuseIdentifier:NSStringFromClass([ZMyOrderInfoCell class])];
    
    UIView *viewBottom = [[UIView alloc] initWithFrame:CGRectMake(0, kScreen_Height - 44 - TabbarSafeBottomMargin, kScreen_Width, 44 + TabbarSafeBottomMargin)];
    viewBottom.backgroundColor = kColorWithHex(0x70be68);
    [self.view addSubview:viewBottom];
    
    UIButton *btnSubmit = [UIButton buttonWithType:UIButtonTypeCustom];
    btnSubmit.frame = CGRectMake(0, 0, kScreen_Width, 44);
    [btnSubmit setTitle:@"提交预订单" forState:UIControlStateNormal];
    [btnSubmit setTitleColor:kColorWithHex(0xffffff) forState:UIControlStateNormal];
    btnSubmit.titleLabel.font = [UIFont systemFontOfSize:16];
    [btnSubmit addTarget:self action:@selector(btnSubmitClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [viewBottom addSubview:btnSubmit];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1 + self.submitOrderArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }else{
        ZMyOrderCarOrderModel *model = [self.submitOrderArray objectAtIndexSafe:section - 1];
        return model.parts.count + 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            ZOrderShipingAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZOrderShipingAddressCell class]) forIndexPath:indexPath];
            if (self.addressModel) {
                cell.shipingAddressModel = self.addressModel;
            }else
            {
                cell.viewNoneAddress.hidden = NO;
                cell.viewAddress.hidden = YES;
            }
            return cell;
        }else{
            UITableViewCell *cell = [UITableViewCell new];
            cell.contentView.backgroundColor = kColorWithHex(0xf2f2f2);
            return cell;
        }
    }else{
        ZMyOrderCarOrderModel *model = [self.submitOrderArray objectAtIndexSafe:indexPath.section - 1];
        if (indexPath.row == 0) {
            ZMyOrderShopInfoTopCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZMyOrderShopInfoTopCell class]) forIndexPath:indexPath];
            cell.model = model;
            return cell;
        }else{
            BShopPartModel *partModel = [model.parts objectAtIndexSafe:indexPath.row - 1];
            ZMyOrderInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZMyOrderInfoCell class]) forIndexPath:indexPath];
            cell.partModel = partModel;
            cell.isOrderDetail = NO;
            return cell;
        }
        return [UITableViewCell new];
    }
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 16;
        }else if (indexPath.row == 1) {
            return UITableViewAutomaticDimension;
        }else{
            return 10;
        }
    }else{
        if (indexPath.row == 0) {
            return [ZMyOrderShopInfoTopCell cellHeight];
        }else{
            return [ZMyOrderInfoCell cellHeight];
        }
        return 0;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 1) {
        ZMyAddressVC *vc = [ZMyAddressVC new];
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - ZMyAddressVCDelegate
- (void)addressVCSelectedModel:(ZMyAddressModel *)addressModel{
    if (addressModel) {
        NSData *data = [USER_DEFAULT objectForKey:DEFAULT_ADDRESS];
        ZMyAddressModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        
        //点击或者点击默认 传回的地址状态
        self.haveSelectedAddress = YES;
        self.is_default = model.is_default;
        self.addressModel = addressModel;
        [self.tableView reloadData];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark - ZMyOrderSubmitSuccessViewDelegate
- (void)orderSubmitSuccessViewClickBtnOk{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 交互事件
- (void)btnSubmitClickAction:(UIButton *)sender{
    if (_isRequesting) {
        return;
    }
    if (self.addressModel.address.length > 0) {
        _isRequesting = YES;
        
        __block NSString *orderIDStr = @"";//订单ID拼接
        [self.submitOrderArray enumerateObjectsUsingBlock:^(ZMyOrderCarOrderModel  * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj.parts enumerateObjectsUsingBlock:^(BShopPartModel * _Nonnull objPart, NSUInteger idx, BOOL * _Nonnull stop) {
                orderIDStr = [orderIDStr stringByAppendingString: orderIDStr.length > 0 ? [NSString stringWithFormat:@",%@",objPart.Id] : objPart.Id];
            }];
        }];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObjectIfNotNil:@"2" forKey:@"user_type"];//2所有经销商 1维修工
        [dict setObjectIfNotNil:self.addressModel.Id forKey:@"address"];
        [dict setObjectIfNotNil:orderIDStr forKey:@"ids"];
        [NetWorkTool POST:submitOrderCar param:dict success:^(id dic) {
            ZMyOrderSubmitSuccessView *viewNotice = [[ZMyOrderSubmitSuccessView alloc] init];
            viewNotice.delegate = self;
            [viewNotice showView];
            //更新预订车数据
            [[NSNotificationCenter defaultCenter] postNotificationName:USER_ADD_ORDER_SUCCESS object:nil];
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
            self->_isRequesting = NO;
        } fail:^(NSError *error) {
            self->_isRequesting = NO;
        } needUser:YES];
        
    }else{
        ShowToastWithText(@"请选择你的收货地址");
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
